JavaScript syntax
part 32/59 · 107.4 KB total
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
JavaScript supports the following binary arithmetic operators:
| + | addition |
|---|---|
| - | subtraction |
| * | multiplication |
| / | division (returns a floating-point value) |
| % | modulo (returns the remainder) |
| ** | exponentiation |
JavaScript supports the following unary arithmetic operators:
| + | unary conversion of string to number |
|---|---|
| - | unary negation (reverses the sign) |
| ++ | increment (can be prefix or postfix) |
| -- | decrement (can be prefix or postfix) |
let x = 1;
console.log(++x); // x becomes 2; displays 2
console.log(x++); // displays 2; x becomes 3
console.log(x); // x is 3; displays 3
console.log(x--); // displays 3; x becomes 2
console.log(x); // displays 2; x is 2
console.log(--x); // x becomes 1; displays 1
The modulo operator displays the remainder after division by the modulus. If negative numbers are involved, the returned value depends on the operand.
const x = 17;
console.log(x%5); // displays 2
console.log(x%6); // displays 5
console.log(-x%5); // displays -2
console.log(-x%-5); // displays -2
console.log(x%-5); // displays 2
To always return a non-negative number, users can re-add the modulus and apply the modulo operator again:
const x = 17;
console.log((-x%5+5)%5); // displays 3
Users could also do:
const x = 17;
console.log(Math.abs(-x%5)); // also 3
Assignment
| = | assign |
|---|---|
| += | add and assign |
| -= | subtract and assign |
| *= | multiply and assign |
| /= | divide and assign |
| %= | modulo and assign |
| **= | exponentiation and assign |
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────